const entityMap = {
  '&': '&amp;',
  '<': '&lt;',
  '>': '&gt;',
  '"': '&quot;',
  "'": '&#39;'
};

function escapeHtml(value) {
  return String(value).replace(/[&<>"']/g, function (s) {
    return entityMap[s];
  });
}

function html_escape_over_code_blocks(value, is_first=true) {
  var result = '';
  if (!value) {
    return result;
  }

  const separator = is_first ? "```" : "`";
  const values = value.split(separator);
  const size = values.length;
  for (var i = 0; i < size; i++) {
      var part = values[i];
      if (i % 2 && size - i > 1) {
          result += separator + part + separator;
      } else if (is_first) {
          result += html_escape_over_code_blocks(part, false);
      } else {
          result += escapeHtml(part);
      }
  }
  return result;
}